
import AMapLoader from '@amap/amap-jsapi-loader';
import './Weather.css';
import { useEffect, useState } from 'react';
import { formateweek } from '../lib/week.js'
function Weather() {
    const [city, setCity] = useState('北京市')//setCity是异步函数
    const [weather, setWeather] = useState({})//事实天气数据
    const [fuweather, setFuweather] = useState({})//未来天气全部数据
    const [fuforecasts, setFuforecasts] = useState([])//未来的天气数组
    useEffect(() => {
        window._AMapSecurityConfig = {
            securityJsCode: "15bc74671d18d0e60f71281b156f8144",
        };
        AMapLoader.load({
            key: "72726cecb5e2d75ebfab500d3bb379b5", // 申请好的Web端开发者Key，首次调用 load 时必填
            version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
            plugins: ["AMap.Scale"], //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
        }).then((AMap) => {
            //高德地图插件已生效
            //获取城市定位
            getLocalCity(AMap)
        })
    }, [])


    const getLocalCity = (AMap) => {
        AMap.plugin('AMap.CitySearch', function () {
            var citySearch = new AMap.CitySearch()
            citySearch.getLocalCity(function (status, result) {
                if (status === 'complete' && result.info === 'OK') {
                    // 查询成功，result即为当前所在城市信息
                    console.log(result.city);
                    setCity(result.city)
                    //获取所在城市的天气
                    getWeather(AMap, result.city)
                    getFutureWeather(AMap, result.city)
                }
            })
        })
    }
    const getWeather = (AMap, city) => {
        //加载天气查询插件
        AMap.plugin("AMap.Weather", function () {
            //创建天气查询实例
            var weather = new AMap.Weather();
            //执行实时天气信息查询
            weather.getLive(city, function (err, data) {
                console.log(err, data);
                //err 正确时返回 null
                //data 返回实时天气数据，返回数据见下表
                setWeather(data)
            });
        });
    }
    const getFutureWeather = (AMap, city) => {
        //加载天气查询插件
        AMap.plugin("AMap.Weather", function () {
            //创建天气查询实例
            var weather = new AMap.Weather();
            //执行实时天气信息查询
            weather.getForecast(city, function (err, data) {
                console.log(err, data);
                console.log(data.forecasts);

                //err 正确时返回 null
                //data 返回天气预报数据，返回数据见下表
                setFuweather(data)
                setFuforecasts(data.forecasts)
            });
        });
    }
    function judg(forecasts) {
        switch (forecasts.dayWeather) {
            case "晴":
                return "./sunny.png"
            case "小雨":
                return "./lightrain.png"
            case "晴转多云":
                return "./sunnytoclody.png"
            case "大雨":
                return "./heavyrain.png"
            default:
                return ""
        }
    }
    return (
        <div className="weather">
            <div className="hd">
                <div className="city">
                    <i className="iconfont icon-dingwei"></i>
                    {city}
                </div>
                <div className="changeCity">
                    <div className="changeCity-btn">
                        <i className="iconfont icon-24gf-city2"></i>
                        切换城市
                    </div>
                </div>
            </div>
            <div className="bd">
                <div className="today">
                    <div className="today-temp">
                        <div className="temp-info">{weather.temperature}℃</div>
                        <div className="weather-info">{weather.weather}</div>
                    </div>
                    <div className="today-wind">
                        <ul>
                            <li>
                                <i className="iconfont icon-shuidi"></i>
                                <p className="category">湿度</p>
                                <p className="value">{weather.humidity}%</p>
                            </li>
                            <li>
                                <i className="iconfont icon-fengxiang"></i>
                                <p className='category'>风向</p>
                                <p>{weather.windDirection}风</p>
                            </li>
                            <li>
                                <i className="iconfont icon-fengli"></i>
                                <p className='category'>风力</p>
                                <p>{weather.windPower}</p>
                            </li>
                        </ul>
                    </div>
                </div>
                <div className="future">
                    <div className="title">三日天气预报</div>
                    <ul className="future-list">
                        {
                            fuforecasts.map((forecasts) => {
                                return (
                                    <li key={forecasts.data} className='future-item'>
                                        <div className="week">{formateweek(forecasts.week)}</div>
                                        <div className="pic">
                                            <img src="{judg(forecasts.dayWeather)}" alt="" />
                                        </div>
                                        <div className="max-min">{forecasts.dayTemp}℃ / {forecasts.nightTemp}℃</div>
                                    </li>
                                )
                            }
                            )
                        }
                    </ul>
                </div>
                <div className="tendency"></div>
            </div>
            <div className="container"></div>
        </div>
    )
}

export default Weather





// import AMapLoader from '@amap/amap-jsapi-loader';
// import './Weather.css';
// import { useEffect, useState } from 'react';

// function Weather() {
//     const [city, setCity] = useState('北京市');
//     const [weather, setWeather] = useState({});
//     const [fuweather, setFuweather] = useState({});
//     const [fuforecasts, setFuforecasts] = useState([]);

//     useEffect(() => {
//         window._AMapSecurityConfig = {
//             securityJsCode: "15bc74671d18d0e60f71281b156f8144",
//         };
//         AMapLoader.load({
//             key: "72726cecb5e2d75ebfab500d3bb379b5",
//             version: "2.0",
//             plugins: ["AMap.Scale"],
//         }).then((AMap) => {
//             getLocalCity(AMap);
//         }).catch((error) => {
//             console.error('Failed to load AMap:', error);
//         });
//     }, []);

//     const getLocalCity = (AMap) => {
//         AMap.plugin('AMap.CitySearch', function () {
//             var citySearch = new AMap.CitySearch();
//             citySearch.getLocalCity(function (status, result) {
//                 if (status === 'complete' && result.info === 'OK') {
//                     console.log(result.city);
//                     setCity(result.city);
//                     getWeather(AMap, result.city);
//                     getFutureWeather(AMap, result.city);
//                 } else {
//                     console.error('Failed to get local city:', status, result);
//                 }
//             });
//         });
//     }

//     const getWeather = (AMap, city) => {
//         AMap.plugin("AMap.Weather", function () {
//             var weather = new AMap.Weather();
//             weather.getLive(city, function (err, data) {
//                 if (err) {
//                     console.error('Failed to get live weather:', err);
//                 } else {
//                     setWeather(data);
//                 }
//             });
//         });
//     }

//     const getFutureWeather = (AMap, city) => {
//         AMap.plugin("AMap.Weather", function () {
//             var weather = new AMap.Weather();
//             weather.getForecast(city, function (err, data) {
//                 if (err) {
//                     console.error('Failed to get future weather:', err);
//                 } else {
//                     setFuweather(data);
//                     setFuforecasts(data.forecasts);
//                     console.log(data.forecasts);

//                 }
//             });
//         });
//     }

//     const getWeatherImage = (data) => {
//         switch (data) {
//             case "晴":
//                 return "./sunny.png";
//             case "晴转多云":
//                 return "./sunnytoclody.png";
//             case "小雨":
//                 return "./lightrain.png";
//             case "大雨":
//                 return "./heavyrain.png";
//             default:
//                 return "";
//         }
//     }

//     return (
//         <div className="weather">
//             <div className="hd">
//                 <div className="city">
//                     <i className="iconfont icon-dingwei"></i>
//                     {city}
//                 </div>
//                 <div className="changeCity">
//                     <div className="changeCity-btn">
//                         <i className="iconfont icon-24gf-city2"></i>
//                         切换城市
//                     </div>
//                 </div>
//             </div>
//             <div className="bd">
//                 <div className="today">
//                     <div className="today-temp">
//                         <div className="temp-info">{weather.temperature}℃</div>
//                         <div className="weather-info">{weather.weather}</div>
//                     </div>
//                     <div className="today-wind">
//                         <ul>
//                             <li>
//                                 <i className="iconfont icon-shuidi"></i>
//                                 <p className="category">湿度</p>
//                                 <p className="value">{weather.humidity}%</p>
//                             </li>
//                             <li>
//                                 <i className="iconfont icon-fengxiang"></i>
//                                 <p className='category'>风向</p>
//                                 <p>{weather.windDirection}风</p>
//                             </li>
//                             <li>
//                                 <i className="iconfont icon-fengli"></i>
//                                 <p className='category'>风力</p>
//                                 <p>{weather.windPower}</p>
//                             </li>
//                         </ul>
//                     </div>
//                 </div>
//                 <div className="future">
//                     <div className="title">三日天气预报</div>
//                     <ul className="future-list">
//                         {fuforecasts.map((forecast, index) => (
//                             <li key={index} className='future-item'>
//                                 <div className="week">
//                                     周{forecast.week}
//                                 </div>
//                                 <div className="pic">
//                                     <img src={getWeatherImage(forecast.dayWeather)} alt="" />
//                                 </div>
//                                 <div className="max-min">{forecast.dayTemp}℃ / {forecast.nightTemp}℃</div>
//                             </li>
//                         ))}
//                     </ul>
//                 </div>
//             </div>
//         </div>
//     );
// }

// export default Weather;